import { _decorator, Component, instantiate, Node, NodePool, Prefab } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('objPool')
export class objPool {

    static _ins: objPool;

    static get ins() {
        if (this._ins) {
            return this._ins;
        }
        this._ins = new objPool();
        return this._ins;
    }

    prefabPool: { [key: string]: Prefab } = {};
    pool: { [key: string]: NodePool } = {};

    init(poolName: string, prefab: Prefab, num: number = 1) {
        if (!this.pool[poolName]) {
            const _pool = new NodePool();
            this.pool[poolName] = _pool;

            for (let i = 0; i < num; i++) {
                let _node = instantiate(prefab);
                _pool.put(_node)

                this.prefabPool[poolName] = prefab;
            }
        }
    }

    getObj(poolName: string) {
        const _pool = this.pool[poolName];
        if (_pool && _pool.size() > 0) {
            const node = _pool.get()
            node.active = true;
            return node
        }
        else {
            //console.log("对象池 数量不足 新生成",poolName)
            const pre = this.prefabPool[poolName];
            const _node = instantiate(pre);
            return _node
        }
    }
    
    getObj_prefab(_prefab: Prefab) {
        const poolName:string  = _prefab.name
        let _pool = this.pool[poolName];
        if (_pool && _pool.size() > 0) {
            const node = _pool.get()
            node.active = true;
            return node
        }
        else {
            if(!_pool){
                _pool = new NodePool();
                this.pool[poolName] = _pool;
            }
            //console.log("对象池 数量不足 新生成",poolName)
            const pre = this.prefabPool[poolName] = _prefab;
            const _node = instantiate(pre);
            return _node
        }
    }

    removeObj(poolName: string, node: Node) {
        const _pool = this.pool[poolName];
        if (_pool) {
            node.active = false;
            _pool.put(node)
        }

    }

    clearObj(poolName: string) {
        const _pool = this.pool[poolName]
        if (_pool) {
            _pool.clear();
            delete this.pool[poolName]
        }
    }
}


